import json
import sys
from typing import Any, Dict, List
import requests

class NpmDocsServer:
    """NPM文档服务器类"""
    
    def __init__(self):
        self.tools = {
            "com.example.npm/get_docs": {
                "name": "com.example.npm/get_docs",
                "title": "获取NPM文档",
                "description": "获取指定NPM包的最新文档",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "package": {
                            "type": "string", 
                            "description": "NPM包名称"
                        }
                    },
                    "required": ["package"]
                }
            }
        }

    def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
        method = request.get("method")
        request_id = request.get("id")
        params = request.get("params", {})

        if method == "initialize":
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "protocolVersion": "2025-06-18",
                    "capabilities": {
                        "tools": {"listChanged": True},
                        "resources": {},
                    },
                    "serverInfo": {"name": "npm-docs-server", "version": "1.0.0"},
                },
            }
        elif method == "tools/list":
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {"tools": list(self.tools.values())},
            }
        elif method == "tools/call":
            name = params.get("name")
            arguments = params.get("arguments", {})
            try:
                result = self.call_tool(name, arguments)
                return {
                    "jsonrpc": "2.0",
                    "id": request_id,
                    "result": {"content": result},
                }
            except Exception as e:
                return {
                    "jsonrpc": "2.0",
                    "id": request_id,
                    "error": {"code": -32603, "message": str(e)},
                }
        else:
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32601, "message": f"Method {method} not found"},
            }

    def call_tool(self, name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        if name == "com.example.npm/get_docs":
            package = arguments.get("package")
            if not package:
                raise ValueError("必须提供package参数")
            
            try:
                response = requests.get(f"https://registry.npmjs.org/{package}")
                response.raise_for_status()
                package_data = response.json()
                
                latest_version = package_data.get("dist-tags", {}).get("latest")
                latest_version_data = package_data.get("versions", {}).get(latest_version, {})
                
                return [{
                    "type": "text",
                    "text": json.dumps({
                        "name": package_data.get("name"),
                        "version": latest_version,
                        "description": latest_version_data.get("description"),
                        "homepage": latest_version_data.get("homepage"),
                        "repository": latest_version_data.get("repository"),
                        "keywords": latest_version_data.get("keywords"),
                        "license": latest_version_data.get("license"),
                        "dependencies": latest_version_data.get("dependencies")
                    }, indent=2, ensure_ascii=False)
                }]
            except requests.RequestException as e:
                raise ValueError(f"获取NPM包信息失败: {str(e)}")

        else:
            raise ValueError(f"未知工具: {name}")

def main():
    server = NpmDocsServer()
    print("📦 NPM文档服务器已启动，等待连接...", file=sys.stderr)
    
    for line in sys.stdin:
        try:
            request = json.loads(line.strip())
            response = server.handle_request(request)
            print(json.dumps(response, ensure_ascii=False))
            sys.stdout.flush()
        except json.JSONDecodeError:
            print(json.dumps({
                "jsonrpc": "2.0",
                "id": None,
                "error": {"code": -32700, "message": "Parse error"},
            }, ensure_ascii=False))
            sys.stdout.flush()

if __name__ == "__main__":
    main()
